package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmDownOrUpDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WeThreadLocalUtil;
import com.heima.wemedia.config.Tess4jClient;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author xiaquanen
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/7/22 09:57:32
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

   @Autowired
   private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private WmTaskService wmTaskService;




    /**
     * 分页条件查询
     *
     * @param wmNewsPageReqDto
     * @return
     */
    @Override
    public ResponseResult newsList(WmNewsPageReqDto wmNewsPageReqDto) {

        //参数校验
        if(wmNewsPageReqDto.getPage()==null||wmNewsPageReqDto.getSize()==null)
            wmNewsPageReqDto.checkParam();

        //拼接查询条件
        //关键字的模糊查询
        //文章状态的精确查询
        //频道的精确查询
        //时间的范围查询
        LambdaQueryWrapper<WmNews> wmNewsLambdaQueryWrapper = Wrappers.<WmNews>lambdaQuery()
                .eq(wmNewsPageReqDto.getStatus() != null, WmNews::getStatus, wmNewsPageReqDto.getStatus())
                .like(StringUtils.isNotBlank(wmNewsPageReqDto.getKeyword()), WmNews::getTitle, wmNewsPageReqDto.getKeyword())
                .eq(wmNewsPageReqDto.getChannelId() != null, WmNews::getChannelId, wmNewsPageReqDto.getChannelId())
                .ge(wmNewsPageReqDto.getBeginPubDate() != null, WmNews::getCreatedTime, wmNewsPageReqDto.getBeginPubDate())
                .between(wmNewsPageReqDto.getEndPubDate() != null, WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate())
                .eq( WmNews::getUserId, WeThreadLocalUtil.getUserId())
                .orderByDesc(WmNews::getCreatedTime);

        Page page=new Page<>(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize());

        page(page,wmNewsLambdaQueryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult((int) wmNewsPageReqDto.getPage(), (int) wmNewsPageReqDto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }

    /**
     * 文章的上下架
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult downOrUp(WmDownOrUpDto dto) {
        //参数校验
        if(dto == null || dto.getId() == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //判断文章是否发布
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if(wmNews.getStatus()!=9)
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        //修改文章的状态
        wmNewsMapper.update(null,Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        //封装文章id，和上下架状态
        Map<String,Object> hashMap=new HashMap<>();
        hashMap.put("articleId",wmNews.getArticleId());
        hashMap.put("enable",dto.getEnable());
        //修改用户端的文章状态
        kafkaTemplate.send("wm_user_article_xiaqe", JSON.toJSONString(hashMap));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 新增或者修改文章
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        //参数校验
        if(wmNewsDto==null)
            return ResponseResult.errorResult(500,"参数错误");
        //封装实体类
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        //将实体类中的某些属性进行自定义赋值
        if(wmNewsDto.getStatus()!=-1)
            wmNews.setType(null);
        //将照片的集合进行字符串拼接添加到实体类中去
        if(wmNewsDto.getImages()!=null&& !wmNewsDto.getImages().isEmpty()) {
            String images = StringUtils.join(wmNewsDto.getImages(), ",");
            wmNews.setImages(images);
        }
        //进行更新或者修改操作
        updateOrInsert(wmNews);
        //判断文章是否是草稿，要是草稿的话就直接存入wm_news表中即可
        if(wmNewsDto.getStatus()==0)
            return ResponseResult.okResult(null);

        //提取文章内容中的图片
        List<String> imagesUrl=getContentImages(wmNews);

        //将内容中的素材和文章的关联关系添加进入关联表中去
        if(!imagesUrl.isEmpty())
            insertNewSMaterial(wmNews,imagesUrl,0);

        //将封面的图片进行逻辑处理
          //将自动的的封面的图片进行逻辑处理并且进行更新
        List<String> images=new ArrayList<>();
        if(wmNewsDto.getType()==-1)
        {
            if(imagesUrl!=null&&imagesUrl.size()>=1&&imagesUrl.size()<3)
            {
                String string = imagesUrl.get(0);
                images.add(string);
                //就是将内容中的图片添加到封面上来，根据文章图片的多少进行不同的添加，再修改封面类型
                wmNews.setType((short)1);
                wmNews.setImages(StringUtils.join(images,","));
            }
            if(imagesUrl!=null&&imagesUrl.size()>=3)
            {
                 images= imagesUrl.stream().limit(3).collect(Collectors.toList());
                wmNews.setImages(StringUtils.join(images,","));
                wmNews.setType((short)3);
            }
            if(imagesUrl.isEmpty())
            {
                wmNews.setType((short)0);
            }
            updateById(wmNews);
        }
            //再添加封面图片和文章的关系
         insertNewSMaterial(wmNews,images,1);

        //提交去审核
        //wmAutoScanService.autoScanWmNews(wmNews.getId());

        //调用异步去处理文章请求
        wmTaskService.addTask(wmNews);


    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     *
     * 删除文章
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult delNews(Integer id) {
        //查询文章的id，用于同步删除用户端的文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        Long articleId = wmNews.getArticleId();
        //删除文章
        wmNewsMapper.deleteById(id);
        //删除文章和素材的关联
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,id));
        //利用kafka进行同步删除用户端的文章
        kafkaTemplate.send("topic_deleteArticle", JSON.toJSONString(articleId));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void insertNewSMaterial(WmNews wmNews, List<String> imagesUrl, int type) {
        //根据素材的url去查询素材对应的id
        if(imagesUrl!=null&&!imagesUrl.isEmpty()) {
           List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imagesUrl));
            List<Integer> integers = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            wmNewsMaterialMapper.insertNewsMaterial(wmNews.getId(),integers,type);
        }
    }

    /**
     * 获取文章中的图片
     *
     * @param wmNews
     * @return
     */
    private List<String> getContentImages(WmNews wmNews) {
        JSONArray jsonArray = JSONArray.parseArray(wmNews.getContent());
        List<String> imagesUrl = new ArrayList<>();
        for (Object o : jsonArray) {
            JSONObject jsonObject = JSONObject.parseObject(o.toString());
            if(jsonObject.getString("type").equals("image"))
            {
                imagesUrl.add(jsonObject.getString("value"));
            }
        }
        return imagesUrl;
    }

    /**
     * 更新或者添加的方法
     *
     * @param wmNews
     */
    private void updateOrInsert(WmNews wmNews) {

        if(wmNews.getId()==null)
        {
            //封装用户id
            Integer userId = WeThreadLocalUtil.getUserId();
            if(userId==null)
                throw new RuntimeException("用户id不能为空");
            wmNews.setUserId(userId);
            //添加
            wmNews.setCreatedTime(new Date());
            //是否上架，默认是上架
            wmNews.setEnable((short) 1);
            save(wmNews);
        }else
        {
            //修改将原有数据库中的关联字段给删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            //删除之后再更新
            wmNewsMapper.updateById(wmNews);
        }
    }
}
